package com.personal.o2o.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import com.personal.o2o.dto.ImageHolder;
import com.personal.o2o.web.superadmin.AreaController;
import net.coobird.thumbnailator.Thumbnails;

import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;

public class ImageUtil {
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    // 时间格式
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    // 随机数
    private static final Random r = new Random();

    static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    // 处理缩略图
//    public static String generateThumbnail(File thumbbnail, String targetAddr) {
    public static String generateThumbnail(ImageHolder ImageHolder, String targetAddr) {
        // 重命名用户上传文件名
        String realFileName = getRandomFileName();
        // 获取用户上传文件扩展名
//        String extension = getFileExtension(thumbbnail);
        String extension = getFileExtension(ImageHolder.getImageName());
        makeDirPath(targetAddr);
        // 相对路径
        String relativeAddr = targetAddr + realFileName + extension;
        logger.debug("current relativeAddr is:"+relativeAddr);
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("current complete addr is:"+PathUtil.getImgBasePath()+relativeAddr);
        try{
//            Thumbnails.of(thumbbnail).size(200,200)
            Thumbnails.of(ImageHolder.getImage()).size(200,200)
                    .watermark(
                            Positions.CENTER,
                            ImageIO.read(new File(basePath + "/watermark.jpg")),
                            0.25f
                    )
                    .outputQuality(0.8f)
                    .toFile(dest);
        }catch (IOException e){
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径所涉及到的目录，例如/home/picture
     * 那么 home和picture这三个文件夹都得自动创建
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 获取输入文件流的扩展名
     * @return
     */
//    private static String getFileExtension(File cFile) {
    private static String getFileExtension(String fileName) {
//        String originalFileName = cFile.getName();
//        return originalFileName.substring(originalFileName.lastIndexOf("."));
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成随即文件名，当前年月日时分秒+五位随机数
     * @return
     */
    public static String getRandomFileName() {
        // 获取随机的五位数
        int rannum = r.nextInt(89999)+10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr+rannum;
    }

    public static void main(String[] args) throws IOException {
        Thumbnails.of(new File("C:\\Download\\picture\\test.jpg")).size(200, 200)
                .watermark(
                        Positions.CENTER,
                        ImageIO.read(new File(basePath + "/watermark.jpg")),
                        0.25f)
                .outputQuality(0.8f)
                .toFile("C:\\Download\\picture\\testwatermark.jpg");
    }

    /**
     * 删除文件或路径下的所有文件
     * @param storePath
     */
    public static void deleteFileOrPath(String storePath){
        File fileOrPath = new File(PathUtil.getImgBasePath() + storePath);
        if(fileOrPath.exists()){
            // 如果是一个目录的
            if (fileOrPath.isDirectory()) {
                File files[] = fileOrPath.listFiles();
                for (int i=0 ; i<files.length; i++) {
                    files[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }

}
